/**
 * The Community Project
 * Copyright Team1 Productions
 * 
 * Joshua Amick
 * Stephen Cunningham
 * Thema Davis
 * Tomika Dawson
 * Lucie DeCristofaro
 * 
 * All Rights Reserved.
 */

package com.dao;

import java.sql.Timestamp;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Expression;

import com.domain.Announcement;
import com.domain.Email;
import com.domain.User;

public class EmailDAO extends BaseObjectDAO{
	public Email getEmailByKeyId(Long keyId){
		Email email = null;
		if((keyId!=null)&&(keyId>0)){
			Criteria crit = this.getSession().createCriteria(Email.class);
			crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
	       	crit.add(Expression.eq("keyId",keyId));
	       	crit.add(Expression.eq("deleted",false));
	       	List<Email> results = crit.list();
	       	if(results.size()>0)email = results.get(0);
	       	else return null;
		}
		return email;
	}
	
	public Email getEmailByTitle(String subject){
		Email email = null;
		if((subject!=null)&&(subject.equals(""))){
			Criteria crit = this.getSession().createCriteria(Email.class);
			crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
	       	crit.add(Expression.ilike("emailSubject",subject));
	       	crit.add(Expression.eq("deleted",false));
	       	List<Email> results = crit.list();
	       	email = results.get(0);
		}
		return email;
	}
	
	public Email save(Email email) {
		Timestamp now = new Timestamp(System.currentTimeMillis());
		email.setLastModDate(now);
		this.getSession().saveOrUpdate(email);
		this.getSession().flush();
		if((email.getKeyId()!=null)){
			return email;
		}
		else return null;
	}
	
	public Email saveEmail(Long keyId, User user, String emailSubject, String emailMessage, 
			boolean publicEmail, String replyToAddress){
		Email email = new Email();
		Timestamp now = new Timestamp(System.currentTimeMillis());
		email.setCreationDate(now);
		email.setCreatedBy(user);
		email.setLastUpdateUser(user);
		email.setEmailSubject(emailSubject);
		email.setEmailMessage(emailMessage);
		email.setPublicEmail(publicEmail);
		email.setReplyToAddress(replyToAddress);
		email = this.save(email);
		return email;
	}
	
	public List<Email> getAllEmails(){
		Criteria crit = this.getSession().createCriteria(Email.class);
		crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
       	List<Email> results = crit.list();
       	if(results.size()>0)return results;
       	else return null;
	}

	public List<Email> getPendingEmails() {
		Criteria crit = this.getSession().createCriteria(Email.class);
		crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		crit.add(Expression.eq("approved",false));
		crit.add(Expression.eq("deleted",false));
       	List<Email> results = crit.list();
       	if(results.size()>0)return results;
       	else return null;
	}
}
